import axios, {
  AxiosInstance,
  InternalAxiosRequestConfig,
  AxiosError,
  AxiosResponse,
} from 'axios';
import { ElNotification } from 'element-plus';
const service: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: 5000,
});

//请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    return config;
  },
  (err: AxiosError) => {
    ElNotification({
      title: 'Error',
      message: err.message,
      type: 'error',
    });
    return Promise.reject(err);
  }
);

//响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    console.log('🚀拦截器 ~ service.interceptors.response.use ~ response:', response.data);
    if(response.data.code !== 200){
      ElNotification({
        title: 'Error',
        message: response.data.message,
        type: 'error',
      });
    }else{
      return response.data;
    }
    
  },
  (err: AxiosError) => {
    ElNotification({
      title: 'Error',
      message: err.message,
      type: 'error',
    });
    return Promise.reject(err);
  }
);

export default service